package com.yeban.base.day06.homework;

import java.util.Arrays;
import java.util.Scanner;

/**
 * @Desc TODO
 * @Author yeban
 * @Date 2025/10/2
 */

//练习2：定义一个方法，实现数组中元素添加时，数组能够扩容
public class StringTest02 {

    private static int count = 0;

    public static int[] addElement(int[] arr, int number) {

        if (count == arr.length) {        // 数组扩容
            int[] newArr = new int[arr.length * 3 / 2 + 1];
            for (int i = 0; i < arr.length; i++) {
                newArr[i] = arr[i];
            }

            newArr[arr.length] = number;
            count ++;

            return newArr;
        }

        arr[count] = number;
        count ++;
        return arr;
    }

    public static void arrayPrint(int[] arr) {

        System.out.print("[");
        for (int i = 0; i < count; i++) {
            if(i < count - 1) {
                System.out.print(arr[i] + ", ");
            } else {
                System.out.print(arr[i]);
            }
        }
        System.out.print("]");
    }

    public static void main(String[]args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("请输入一个数组长度n：");
        int n = sc.nextInt();
        int[] arr = new int[n];

        if(n >= 0){
            System.out.println("请输入这个数组的各个元素（用空格隔开）：");
            for (int i = 0; i < n; i++) {
                int number = sc.nextInt();
            }
            System.out.print("当前数组：");
            arrayPrint(arr);
        }

        count = arr.length;

        while(true) {
            System.out.println();
            System.out.print("请输入添加的数字：");
            int num = sc.nextInt();
            arr = addElement(arr, num);

            System.out.print("新数组显示：");
            arrayPrint(arr);
            System.out.println();
            System.out.print("新数组真实元素：");
            System.out.println(Arrays.toString(arr));
        }

    }
}
